using System;
using System.Collections;
using BitMango.Diagnostics;
using UnityEngine;

public class TaskRunner
{
	public static TaskRunner Instance
	{
		get
		{
			if (TaskRunner._instance == null)
			{
				TaskRunner.InitInstance();
			}
			return TaskRunner._instance;
		}
	}

	public Coroutine Run(IEnumerable task)
	{
		return this.Run(task.GetEnumerator());
	}

	public Coroutine Run(IEnumerator task)
	{
		if (this._runner != null && this._runner.enabled)
		{
			this._runner.gameObject.SetActive(true);
			return this._runner.StartCoroutine(task);
		}
		return null;
	}

	public void RunSync(IEnumerable task)
	{
		this.RunSync(task.GetEnumerator());
	}

	public void RunSync(IEnumerator task)
	{
		while (task.MoveNext())
		{
		}
	}

	public void RunManaged(IEnumerable task)
	{
		this.RunManaged(task.GetEnumerator());
	}

	public void RunManaged(IEnumerator task)
	{
		if (this._runner != null && this._runner.enabled)
		{
			this._runner.gameObject.SetActive(true);
			this._runner.StartCoroutineManaged(task);
		}
	}

	public void PauseManaged()
	{
		this._runner.paused = true;
	}

	public void ResumeManaged()
	{
		this._runner.paused = false;
	}

	public void Stop()
	{
		if (this._runner != null)
		{
			this._runner.StopAllCoroutines();
		}
	}

	public void Destroy()
	{
		this.Stop();
		if (this._runner != null)
		{
			if (Application.isPlaying)
			{
				UnityEngine.Object.Destroy(this._runner.gameObject);
			}
			else
			{
				UnityEngine.Object.DestroyImmediate(this._runner.gameObject);
			}
		}
		TaskRunner._instance = null;
	}

	private static void InitInstance()
	{
		GameObject gameObject = GameObject.Find("TaskRunner");
		if (gameObject == null)
		{
			gameObject = new GameObject("TaskRunner");
			if (Application.isPlaying)
			{
				UnityEngine.Object.DontDestroyOnLoad(gameObject);
				gameObject.hideFlags = HideFlags.DontSave;
			}
		}
		TaskRunner._instance = new TaskRunner();
		TaskRunner._instance._runner = gameObject.AddComponent<MonoTask>();
	}

	public void ExecuteOnMainThread(Action act)
	{
		Debugger.Assert(this._runner != null);
		this._runner.ExecuteOnMainThread(act);
	}

	private MonoTask _runner;

	private static TaskRunner _instance;
}
